import { URLSearchParamsInit, useSearchParams } from "react-router-dom";
import { useMemo, useState } from "react";
import { cleanObject, subset } from "../utils";

// 返回页面 URL 中，指定 keys 的参数
export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParams] = useSearchParams();
  const [stateKeys] = useState(keys);
  const setSearchParams = useSetUrlQueryParam();
  return [
    useMemo(
      () => subset(Object.fromEntries(searchParams), stateKeys),
      [searchParams, stateKeys]
    ),
    (params: Partial<{ [key in K]: unknown }>) => setSearchParams(params),
  ] as const;
};

export const useSetUrlQueryParam = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  return (params: Partial<{ [key in string]: unknown }>) => {
    const cleanedParams = cleanObject({
      ...Object.fromEntries(searchParams),
      ...params,
    }) as URLSearchParamsInit;
    return setSearchParams(cleanedParams);
  };
};
